package top.wuyang.study.java24.servlet.softwaretype;

import top.wuyang.study.java24.dao.TbSoftwareTypeDAO;
import top.wuyang.study.java24.entity.Result;
import top.wuyang.study.java24.entity.TbSoftwareType;
import top.wuyang.study.java24.util.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "softwareTypeInsertServlet", urlPatterns = "/softwaretype/insert.action")
public class InsertServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        resp.setContentType("application/json");
        try {
            String type_name = req.getParameter("type_name");
            String description = req.getParameter("description");
            // 检测--分类名称不能重复
            TbSoftwareType check = TbSoftwareTypeDAO.queryByName(type_name);
            if (check != null) {
                Result<String> result = Result.fail("分类名称已存在", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            check = new TbSoftwareType();
            check.setType_name(type_name);
            check.setDescription(description);
            int i = TbSoftwareTypeDAO.insert(check);
            if (i == 1) {
                Result<String> result = Result.success("添加成功", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            Result<String> result = Result.fail("添加失败", null);
            writer.println(JsonUtils.stringify(result));


        } catch (Exception e) {
            e.printStackTrace();
            Result<String> result = Result.fail("添加发生错误", null);
            writer.println(JsonUtils.stringify(result));
        }
    }


}
